import React,{Component} from 'react'
import {createPortal} from 'react-dom'
import PropTypes from 'prop-types'
import styles from './style.scss'
export default class Modal extends Component{
	static propTypes={
		children: PropTypes.node,
		visible: PropTypes.bool,
		style: PropTypes.object,
		onClose: PropTypes.func,
		onConfirm: PropTypes.func,
		onCancel: PropTypes.func,
		renderFooter: PropTypes.func,
		confirmText: PropTypes.string,
		cancelText: PropTypes.string,
		title: PropTypes.string
	}

	constructor(){
		super()
		const doc = window.document
		this.node = doc.createElement('div')
		doc.body.appendChild(this.node)
	}

	componentWillUnmount() {
		window.document.body.removeChild(this.node)
	}
    
    onClose = () => {
    	this.props.onClose && this.props.onClose()
    }
    onConfirm = () => {
    	this.props.onConfirm && this.props.onConfirm()
    }
    onCancel = () => {
    	this.props.onCancel && this.props.onCancel()
    }
	
    render(){
    	let {visible=false,style,renderFooter,confirmText='',cancelText='',title='默认标题'}=this.props
    	let modalStyle = {
    		width:'500px',
    		height:'500px'
    	}
    	if(style){
    		modalStyle = style
    	}
    	if(visible){
    		return createPortal(<div className={styles['modal-wrap']}>
    			<div className={styles['modal-mask']} />
    			<div className={styles['content-box']} style={modalStyle}>
    				<div className={styles['header']}>
    					{title}
    					<a onClick={this.onClose}>×</a>
    				</div>
    				<div className={styles['content']}>
    					{this.props.children}
    				</div>
    				<div className={styles['footer']}>
    					{
    						renderFooter?renderFooter():<div>
    							<button onClick={this.onConfirm}>{confirmText!=''?confirmText:'确定'}</button>
    							<button onClick={this.onCancel}>{cancelText!=''?cancelText:'取消'}</button>
    						</div>
    					}
    				</div>
					
    			</div>
    		</div>,this.node)
    	}else{
    		return null
    	}
    }
}